package com.yaowk.platform.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.yaowk.authc.model.User;
import com.yaowk.common.kit.ResultKit;
import com.yaowk.common.validator.RequiredIdValidator;
import com.yaowk.platform.model.Advertising;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.Date;
import java.util.List;

/**
 * 广告管理
 *
 * @authc yaowk
 * 2017/5/3
 */
public class AdvertisingController extends Controller {

    /**
     * 广告列表
     *
     * @param id|广告id|Integer|必填
     * @title 广告列表
     */
    @Before(RequiredIdValidator.class)
    @RequiresPermissions("platform:read")
    public void list() {
        List<Advertising> advertisingList = Advertising.dao.findByPlatformId(getParaToInt("id"));
        renderJson(ResultKit.success(advertisingList));
    }


    /**
     * 添加广告
     *
     * @param space_id|广告位id|Integer|必填
     * @param title|标题|String|否
     * @param url|链接|String|否
     * @param image|图片|String|否
     * @title 添加广告
     */
    @RequiresPermissions("platform:update")
    public void add() {
        Advertising advertising = getModel(Advertising.class, "");
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        advertising.setCreateUser(user.getId())
                .setCreateTime(new Date())
                .save();
        renderJson(ResultKit.success(this));
    }

    /**
     * 编辑广告
     *
     * @param id|广告id|Integer|必填
     * @param title|标题|String|否
     * @param url|链接|String|否
     * @param image|图片|String|否
     * @title 编辑广告
     */
    @RequiresPermissions("platform:update")
    public void edit() {
        Advertising advertising = getModel(Advertising.class, "");
        Advertising old = Advertising.dao.findById(advertising.getId());
        old.setTitle(advertising.getTitle())
                .setUrl(advertising.getUrl())
                .setImage(advertising.getImage())
                .update();
        renderJson(ResultKit.success(this));
    }

    /**
     * 删除广告
     *
     * @param id|广告id|Integer|必填
     * @title 删除广告
     */
    @RequiresPermissions("platform:update")
    @Before(RequiredIdValidator.class)
    public void remove() {
        Advertising advertising = Advertising.dao.findById(getParaToInt("id"));
        advertising.setStatus(0).update();
        renderJson(ResultKit.success(this));
    }
}
